package cn.edu.ctbu.firstdata.service.Impl;


import cn.edu.ctbu.firstdata.domain.Student;
import cn.edu.ctbu.firstdata.exception.REnum;
import cn.edu.ctbu.firstdata.exception.RException;
import cn.edu.ctbu.firstdata.repository.StudentRepository;
import cn.edu.ctbu.firstdata.service.IStudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import org.springframework.data.domain.Pageable;
import java.util.List;

/**
 * 学生服务处，用于访问学生的数据业务逻辑
 */
@Service
public class StudentServiceImp implements IStudentService {

    /**
     * 取所有的学生
     * @return 返回读到的学生信息
     */
    @Autowired
    private StudentRepository studentRepository;
    public Page<Student> getall(Pageable pageable){
        return studentRepository.findAll(pageable);
    }

    @Override
    public List<Student> getall() {
        return studentRepository.findAll();
    }

    public List<Student> getall(Example<Student> example){
        return studentRepository.findAll();
    }

    /**
     * 通过姓名来查询对应的学生列表
     * @return 指定姓名的学生列表
     */
    public List<Student> findByName(String studentName){
        return studentRepository.findByName(studentName);
    }
    public List<Student> findByNameLike(String studentName){
        return studentRepository.findByName("%"+studentName+"%");
    }
    public Student findById(Integer id)
    {
        return studentRepository.findById(id).orElse(null);
    }
    public List<Student> getStudentScoreLess(Integer score)
    {
        return studentRepository.getByStudentsScoreLess(score);
    }
    /**
     * 新增和更新单个学生
     * @param student
     * @return
     */
    @Transactional
    public Student save(Student student){
        return studentRepository.save(student);
    }
    /**
     * 删除单个学生
     * @param student
     * @return
     */
    @Transactional
    public void delete(Student student){
        studentRepository.delete(student);
    }

    @Override
    public Page<Student> findAll(Pageable pageable) {
        return studentRepository.findAll(pageable);
    }

    @Override
    public Page<Student> findBySex(Integer sex,Pageable pageable) {
        return studentRepository.findBySex(sex,pageable);
    }

    @Override
    public boolean validUserNameAndPassword(String userName, String password) throws Exception {
        List<Student> students = studentRepository.findByNameAndPassword(userName,password);
        if(students.size()>0){
            return true;
        }
        else{
            throw new RException(REnum.LOGIN_ERR);
        }
    }


    /**
     * 删除单个学生
     * @param
     * @return
     */
    @Transactional
    public void delete(Integer id){
        studentRepository.deleteById(id);
    }
}
